package tables

import (
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/validation"
)

type Users struct {
	Id       int    `form:"-"`
	Name     string `orm:"size(20)" valid:"Required; MinSize(2); MaxSize(10)" form:"name"`
	Username string `orm:"size(50);unique;index" valid:"Required; MinSize(5); MaxSize(30); AlphaNumeric" form:"username"`
	Password string `orm:"size(50)" valid:"Required; MinSize(5); MaxSize(20); AlphaDash" form:"password"`

	UserRoleses []*UserRoles `orm:"reverse(many)"`
	Tokens      *Tokens      `orm:"rel(one);"`
}

func (u *Users) TableIndex() [][]string {
	return [][]string{
		[]string{"Username", "Password"},
	}
}

func (u *Users) TableName() string {
	return "users"
}

func (u *Users) Valid(v *validation.Validation) {
	o, username := orm.NewOrm(), u.Username
	//判断用户是否已经注册过
	exist := o.QueryTable("users").Filter("Username", username).Exist()
	//已经注册过，报错
	if exist {
		v.SetError("Username", "该用户已注册过")
	}
}

func (u *Users) AddUser() (uid int64, err error) {
	o := orm.NewOrm()
	uid, err = o.Insert(u)
	return uid, err
}

func (u *Users) GetByUid(uid int) (Users) {
	o, user := orm.NewOrm(), Users{Id: uid}
	o.Read(&user)
	return user
}

func (u *Users) GetByUsernameAndPassword(username string, password string) (Users, error) {
	o := orm.NewOrm()
	err := o.QueryTable(u).Filter("username", username).Filter("password", password).One(u)
	return *u, err
}

func (u *Users) GetUserNum() int64 {
	o := orm.NewOrm()
	cnt, _ := o.QueryTable(u).Count()
	return cnt
}
